<template>
  <div class="app-container scrollable-y">
    <div class="app-content-container pd20">
      <!-- 查询条件 -->
      <el-row>
        <el-form :inline="true" :label-width="labelWidth+'px'">
          <el-row>
            <el-form-item label="小程序">
              <el-select v-model="query.appid" clearable>
                <el-option v-for="item in $store.getters.user.maList" :key="item.id" :label="item.maName" :value="item.maId"/>
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="下单时间">
              <date-picker :value.sync="query.dateTimes" :default-value="query.dateTimes" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="订单状态">
              <el-radio-group v-model="query.status" @change="getList">
                <el-radio>全部</el-radio>
                <el-radio :label="10">待支付</el-radio>
                <el-radio :label="20">待发货</el-radio>
                <el-radio :label="26">配送中</el-radio>
                <el-radio :label="30">退货申请</el-radio>
                <el-radio :label="60">已完成</el-radio>
                <el-radio :label="40">退款完成</el-radio>
                <el-radio :label="31">取消退款</el-radio>
                <el-radio :label="12">已过期</el-radio>
                <el-radio :label="11">已取消</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="订单搜索">
              <el-input v-model="orderSearchValue" style="width: 350px" clearable @keydown.enter.native="getList($event)">
                <el-select style="width:120px" v-model="orderSearchType" slot="prepend" placeholder="请选择">
                  <el-option v-for="item in orderSearchTypes" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-input>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="商品搜索">
              <el-input v-model="skuSearchValue" style="width: 350px" clearable @keydown.enter.native="getList($event)">
                <el-select style="width:120px" v-model="skuSearchType" slot="prepend" placeholder="请选择">
                  <el-option v-for="item in skuSearchTypes" :key="item.value" :label="item.name" :value="item.value"/>
                </el-select>
              </el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </el-row>
      <!-- 操作 -->
      <el-row class="mb20" :style="{ marginLeft: labelWidth+'px' }">
        <el-button type="primary" size="small" @click="getList">
          <svg-icon icon-class="search"/>
          <span>查询</span>
        </el-button>
        <el-button plain size="small" @click="handleExport">
          <svg-icon icon-class="export"/>
          <span>导出</span>
        </el-button>
      </el-row>
      <!-- 订单列表 -->
      <div v-if="orderList.length > 0" class="cart-list-wrapper">
        <el-row v-for="(order, index) in orderList" :key="index" class="mb20">
          <el-col :span="18">
            <el-card class="box-card">
              <div slot="header" class="card-header flex align-center flex-justify-center">
              <span class="text-xl text-bold mr15">
                <el-tag effect="plain" type="info" style="color: #515a6e; border-color: #17233d;">{{ index + 1 }}</el-tag>
              </span>
                <span class="text-xl text-bold mr15">
                <el-tag v-if="order.status === 60 || order.status === 40" effect="dark" type="success">
                  {{ selectDictLabel(statusOptions, order.status) }}
                </el-tag>
                <el-tag v-else-if="order.status === 11" effect="dark" type="info">
                  {{ selectDictLabel(statusOptions, order.status) }}
                </el-tag>
                <el-tag v-else-if="order.status === 10 || order.status === 20 || order.status === 26" effect="plain"  style="color: #515a6e; border-color: #17233d;" type="info">
                  {{ selectDictLabel(statusOptions, order.status) }}
                </el-tag>
                <el-tag v-else-if="order.status === 30" effect="dark" type="danger">
                  {{ selectDictLabel(statusOptions, order.status) }}
                </el-tag>
                <el-tag v-else effect="dark" type="warning">
                  {{ selectDictLabel(statusOptions, order.status) }}
                </el-tag>
              </span>
                <div class="flex-sub flex justify-end align-center">
                  <el-button type="text" @click="onClickRemark(index)">备注</el-button>
                  <Poptip
                    v-if="order.delivery.isSub != '1' && order.status == 26"
                    confirm
                    title="是否要订阅快递信息"
                    ok-text="确定"
                    @on-ok="onClickSubscribe(index)"
                    cancel-text="取消">
                    <el-button class="mr15 m15" type="text">订阅快递消息</el-button>
                  </Poptip>
                  <Poptip
                    v-if="order.delivery.isSub != '1' && order.status == 40"
                    confirm
                    title="是否要通知客户退款进度"
                    ok-text="确定"
                    @on-ok="onNotifyRefund(index)"
                    cancel-text="取消">
                    <el-button class="mr15 m15" type="text">退款通知</el-button>
                  </Poptip>
                  <el-button type="text">导出</el-button>
                </div>
              </div>
              <div class="card-body">
                <el-row v-if="order.status === 26 || order.status === 60">
                  <div class="mb5" v-if="order.delivery.nu">运单号：{{order.delivery.nu}}</div>
                  <el-collapse class="mb15" v-if="order.delivery.nu">
                    <el-collapse-item>
                      <template slot="title">
                        <div class="flex-1 mr20">{{order.delivery.company}}</div>
                        <div class="flex-1 mr20">
                          {{selectDictLabel(stateOptions, order.delivery.state)}}
                        </div>
                        <el-tooltip v-if="order.trackItems && order.trackItems.length > 0"
                                    class="item flex-1" effect="dark" style="width: 50%"
                                    :content="order.trackItems[order.trackItems.length-1].context" placement="top">
                        <span class="mr20" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                          {{order.trackItems[order.trackItems.length-1].context}}
                        </span>
                        </el-tooltip>
                      </template>
                      <el-timeline v-if="order.trackItems && order.trackItems.length > 0">
                        <el-timeline-item
                          v-for="(item, index) in order.trackItems"
                          :key="index"
                          type="primary"
                          size="large"
                          :timestamp="$moment(item.ftime).format('YYYY-MM-DD HH:mm:ss')">
                          {{item.context}}
                        </el-timeline-item>
                      </el-timeline>
                    </el-collapse-item>
                  </el-collapse>
                </el-row>
                <div class="mb15">
                  <el-row class="mb5">
                    <el-col :span="12">
                      <span class="text-normal mr10">订单号：{{ order.orderNo }}</span>
                    </el-col>
                    <el-col :span="12">
                      <span class="text-normal mr10">订单Id：{{ order.id }}</span>
                    </el-col>
                  </el-row>
                  <el-row class="mb5">
                    <el-col :span="12">
                      <span class="mr20">顾客姓名：{{order.delivery.addressName}}</span>
                      <span>联系电话：{{order.delivery.addressPhone}}</span>
                    </el-col>
                    <el-col :span="12">
                      <span>openId：{{order.openId}}</span>
                    </el-col>
                  </el-row>
                  <el-row class="mb5">
                    <span>顾客地址：{{order.delivery.totalAddress}}{{order.delivery.addressCity}}{{order.delivery.address}}</span>
                  </el-row>
                </div>
                <el-row class="mb15">
                  <el-collapse>
                    <el-collapse-item>
                      <template slot="title">
                        <div class="flex flex-justify-center flex-items-center">
                          <span class="text-normal">共 {{ order.orderItems.length }} 件商品，实付金额</span>
                          <span class="ml5 text-danger" style="font-weight: bold;font-size:17px">¥{{order.payFee}}</span>
                        </div>
                      </template>
                      <div >
                        <el-table :data="order.orderItems" style="width:100%">
                          <el-table-column width="100">
                            <template slot-scope="scope">
                              <el-image :src="'http://192.168.2.99/v1/image/'+scope.row.itemHome" fit="contain"></el-image>
                            </template>
                          </el-table-column>
                          <el-table-column label="商品名称" prop="itemName" column-key="itemName"></el-table-column>
                          <el-table-column label="商品编码" prop="itemCode" column-key="itemCode"></el-table-column>
                          <el-table-column label="总重量" prop="weight" column-key="weight"></el-table-column>
                          <el-table-column label="数量" prop="itemCount" column-key="itemCount"></el-table-column>
                          <el-table-column label="实际金额" prop="payFee" column-key="payFee"></el-table-column>
                          <el-table-column label="原价金额" prop="itemTotal" column-key="itemTotal"></el-table-column>
                        </el-table>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </el-row>
                <el-row>
                  <span v-if="order.storeRemark">商家备注：{{order.storeRemark}}</span>
                </el-row>
                <el-row>
                  <span class="text-muted mr20">创建时间：{{ order.createTime }}</span>
                  <span v-if="order.status > 12" class="text-muted mr20">支付时间：{{ order.payTime }}</span>
                  <div v-if="order.status === 60 || order.status === 40">
                    <span class="text-muted">完成时间：{{ order.updateTime }}</span>
                  </div>
                </el-row>
                <el-row class="flex-sub" style="text-align: right">
                  <el-button plain size="small" @click="onClickSend(index)" v-if="order.status === 20">确认发货</el-button>
                  <el-button plain size="small" @click="handleRefund(index)" v-else-if="order.status === 30">确认退款</el-button>
                </el-row>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <div v-else-if="!orderList.length && !loading" class="empty-list flex flex-direction justify-center align-center flex-sub" style="position:relative;">
        <div class="flex-sub flex align-center justify-center flex-direction" style="width:240px">
          <svg-icon icon-class="empty" class="empty-list-icon text-light-gray" style="width:100%;height:auto"/>
          <span class="mt20 text-gray">抱歉，没有找到订单~~~</span>
        </div>
      </div>
      <!-- 分页组件 -->
      <el-row v-if="orderList.length > 0" class="flex align-center justify-start mt20">
        <vxe-pager background
                   align="left"
                   class="bg-white"
                   :current-page.sync="query.pageNum"
                   :page-size.sync="query.pageSize"
                   :total.sync="query.total"
                   :page-sizes="[10, 20, 30, 50, 100]"
                   :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                   @page-change="getList"/>
      </el-row>
    </div>
    <Modal
      title="商家备注"
      v-model="showRemarkModal"
      @on-ok="updateOrder">
      <Input v-model="update.remark" :rows="3" maxlength="128" show-word-limit type="textarea" placeholder="请输入订单备注" style="width: 100%" />
    </Modal>
    <Modal
      v-model="showSendModal"
      title="填写快递单"
      @on-ok="confirmSend">
      <Input v-model="update.nu" placeholder="请输入快递单号" style="width: 100%" />
    </Modal>
    <!--  发货窗口  -->
<!--    <vxe-modal v-model="showSendModal"-->
<!--               :esc-closable="true"-->
<!--               :mask-closable="true"-->
<!--               :duration="0"-->
<!--               title="订单发货"-->
<!--               :position="{ top: '15%', left: 'center' }"-->
<!--               width="50%"-->
<!--               max-height="90%"-->
<!--               height="480"-->
<!--               min-height="480"-->
<!--               auto-resize-->
<!--               transfer>-->
<!--      <template v-slot>-->
<!--        &lt;!&ndash; 商品明细 &ndash;&gt;-->
<!--        <vxe-table max-height="400">-->
<!--          <vxe-table-column type="seq" align="center" width="60"></vxe-table-column>-->
<!--          <vxe-table-column field="itemName" header-align="center" title="商品" show-overflow>-->
<!--            <template v-slot="{ row }">-->
<!--              <div class="flex">-->
<!--                <el-image style="width: 64px; height: 64px;" :key="row.itemHome" :src="row.itemHome" lazy><</el-image>-->
<!--                <span>row.itemName </span>-->
<!--              </div>-->
<!--            </template>-->
<!--          </vxe-table-column>-->
<!--          <vxe-table-column field="itemCount" header-align="center" title="数量"></vxe-table-column>-->
<!--          <vxe-table-column field="status" align="center" title="状态"></vxe-table-column>-->
<!--          <vxe-table-column field="status" align="center" title="运单号" show-overflow></vxe-table-column>-->
<!--        </vxe-table>-->
<!--        &lt;!&ndash; 配送信息 &ndash;&gt;-->
<!--        <el-row class="flex mt20 mb20 lh30">-->
<!--          <span>配送信息</span>-->
<!--          <div class="m20">-->
<!--            <div>联系方式：</div>-->
<!--            <div>收货人：</div>-->
<!--            <div>收货地址：</div>-->
<!--          </div>-->
<!--        </el-row>-->
<!--        &lt;!&ndash; 发货方式 &ndash;&gt;-->
<!--        <el-row class="flex mb20 lh30">-->
<!--          <span>发货方式</span>-->
<!--          <div class="m20">-->
<!--            <el-radio label="">自主发单</el-radio>-->
<!--            <el-radio>微信物流助手</el-radio>-->
<!--          </div>-->
<!--        </el-row>-->
<!--      </template>-->
<!--    </vxe-modal>-->
  </div>
</template>

<script>
  import DatePicker from "@/components/DatePicker/index"
  import { listOrder, exportOrder, updateOrder, updateDelivery, subscribe, notifyRefund } from '@/api/mall'
  import request from '@/utils/request'
  import { Loading } from 'element-ui'

  export default {
    name: 'List',
    components: { DatePicker },
    data() {
      return {
        statusOptions: [],
        stateOptions: [],
        showRemarkModal: false,
        showSendModal: false,
        labelWidth: 70,
        loading: false,
        open: false,
        toggleDetail: false,
        orderSearchTypes: [
          { name: '订单号', value: 'orderNo' },
          { name: '手机号', value: 'mobile' },
          { name: '运单号', value: 'nu' }
        ],
        orderSearchType: undefined,
        orderSearchValue: undefined,
        skuSearchTypes: [
          { name: '商品编码', value: 'code' },
          { name: '商品名称', value: 'itemName' }
        ],
        skuSearchType: undefined,
        skuSearchValue: undefined,
        query: {
          appid: undefined,
          pageNum: 1,
          pageSize: 10,
          total: 0,
          status: undefined,
          orderNo: undefined,
          code: undefined,
          dateTimes: []
        },
        update: {
          remark: ''
        },
        selectedIndex: -1,
        orderList: []
      }
    },
    created() {
      this.orderSearchType = this.orderSearchTypes[0].value;
      this.skuSearchType = this.skuSearchTypes[0].value;
      const end = this.getDayEnd()
      const start = this.getDayStart()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      this.query.dateTimes = [start, end]
      this.getDicts("order_status").then(res => {
        this.statusOptions = res.data;
      });
      this.getDicts("delivery_state").then(res => {
        this.stateOptions = res.data
      })
      this.query.appid = this.$store.getters.user.maList[0].maId
      this.getList()
    },
    methods: {
      onNotifyRefund(index) {
        let order = this.orderList[index]
        request({
          url: '/mini/template/uniformSend',
          baseURL: process.env.VUE_APP_WX_BASE_API,
          method: 'post',
          params: {
            openid: order.openId,
            appid: this.query.appid,
            body: {
              orderId: order.id,
              applyTime: order.createTime,
              status: order.status,
              money: order.payFee
            }
          }
        }).then(res => {
          this.msgSuccess('退款通知成功')
        }).catch(res => {
          this.msgError(res.msg)
        })
      },
      onClickSubscribe(index) {
        let order = this.orderList[index]
        subscribe({ nu: order.delivery.nu }, { appid: this.query.appid }).then(res => {
          this.msgSuccess('订阅成功')
        })
      },
      onClickRemark(index) {
        this.update.remark = this.orderList[index].storeRemark
        this.selectedIndex = index
        this.showRemarkModal = true
      },
      onClickSend(index) {
        this.update.remark = this.orderList[index].storeRemark
        this.update.nu = this.orderList[index].nu
        this.selectedIndex = index
        this.showSendModal = true
      },
      //更新订单
      updateOrder() {
        const that = this
        updateOrder({
          id: this.orderList[this.selectedIndex].id,
          storeRemark: this.update.remark.trim(),
        }, {
          appid: this.query.appid
        })
          .then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.getList()
            this.selectedIndex = -1
          })
          .catch(res => {
            this.$message({
              message: '修改备注失败，' + res.msg,
              type: 'error'
            })
          })
      },
      // 确认发货
      confirmSend() {
        const that = this
        updateDelivery({
          id: this.orderList[this.selectedIndex].delivery.id,
          nu: this.update.nu.trim(),
        },{
          appid: this.query.appid
        })
          .then(res => {
            this.$message({
              message: '发货成功',
              type: 'success'
            })
            this.getList()
            this.selectedIndex = -1
          })
          .catch(res => {
            this.$message({
              message: '发货失败，' + res.msg,
              type: 'error'
            })
          })
      },
      //调用接口查询订单
      getList(loading) {
        const that = this
        let data = this._.cloneDeep(this.query)
        data[this.orderSearchType] = this.orderSearchValue
        data[this.skuSearchType] = this.skuSearchValue
        let loadingInstance = undefined
        if (loading) {
          loadingInstance = Loading.service({
            target: ".app-main",
            text: "加载中",
            spinner: "el-icon-loading",
            customClass: 'text-white',
            background: "rgba(0,0,0,0.6)",
            lock: true
          })
        }

        setTimeout(() => {
          listOrder(data, {
            appid: this.query.appid
          }).then(response => {
            that.orderList = response.rows;
            console.log(that.orderList)
            that.query.total = response.total;
            that.$nextTick(() => {
              if (loading) {
                loadingInstance.close()
              }
            })
          }).catch(_ => {
            that.$nextTick(() => {
              if (loading) {
                loadingInstance.close()
              }
            })
          });
        }, 300)
      },
      // 导出订单
      handleExport() {
        exportOrder(this.query).then(response => {

        })
      },
      // 退款确认
      handleRefund(index) {
        this.confirm('确认退款吗？', '退款提示')
            .then(type => {
              if (type === 'confirm') {
                let order = this.orderList[index]
                request({
                  url: '/refund/'+order.id,
                  baseURL: process.env.VUE_APP_ORDER_BASE_API,
                  method: 'post',
                  data: {}
                }).then(res => {
                  this.msgSuccess('退款成功')
                  this.getList()
                }).catch(res => {
                  this.msgError(res.message || res.msg)
                })
              }
            })
      },
      // 退款通知
      handleSendRefundMsg(index) {
        let order = this.orderList[index]
        const baseURL = request.defaults.baseURL
        request.defaults.baseURL = '/wx-api'
        request({
          url: '/mini/template/uniformSend',
          method: 'post',
          params: {
            openid: order.openId,
            appid: this.query.appid,
            body: {
              applyTime: order.createTime,
              money: order.payFee,
              orderId: order.id,
              status: 40
            }
          },
        }).then(res => {
          this.msgSuccess("通知发送成功")
        }).catch(res => {
          this.msgError(res.msg)
        })
        request.defaults.baseURL = baseURL
      }
    }
  }
</script>

<style scoped>
  @keyframes ani-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
  }
  .spin-icon-load{
    animation: ani-spin 1s linear infinite;
  }
</style>
